var res;
var selectedWarehouseIndex = -1;
var latitude;
var longitude;
var signed = false;
var isAddressChanged = false;
var oldData = new Array();
var newData = new Array();

var addressPattern = "^[a-zA-Z ,.'-]+$";
var homePattern = "^[a-zA-Z0-9,./'-]+$";
var emailPattern = "(([A-Za-z])|(\\d)|([-_.]))+@([A-Za-z])+[.]([A-Za-z]){2,4}";

function callback_order(param) {
    res = param;
    showAddresses();
    drawRoute(res, 0);
    selectWarehouse();
    countPrice();
}

function isEmptyFields() {
    var flag = true;
    flag = ($("#country").val() == "");
    flag = flag || ($("#city").val() == "");
    flag = flag || ($("#street").val() == "");
    flag = flag || ($("#building").val() == "");
    return flag;
}

function updateLocation() {
    if ($("#change_address_check_box").is(':checked') || (oldData.length == 0))
        $("#location").show();
    isAddressChanged = true;
    newData = new Array();
    newData.push($("#country").val());
    newData.push($("#city").val());
    newData.push($("#street").val());
    newData.push($("#building").val());
    newData.push($("#flat").val());
    if (isEmptyFields()) {
        $("#location").hide();
        $("#order_btn").attr('disabled', true);
        $("#order_btn").hide();
    } else {
        $("#order_btn").attr('disabled', false);
        $("#order_btn").show();
        get_location();
    }
}

//function setCoordinates(lat, long) {
//    latitude = lat;
//    longitude = long;
//}

function get_location() {
    var address = $("#country").val() +
            ", " +
            $("#city").val() +
            ", " +
            $("#street").val() +
            ", " +
            $("#building").val();
    codeAddress(address, callback_order);
}

function showAddresses() {
    if (res.length === 0) {
        location.hide();
    }
    var str = '<div class="block-header-item"><h3>Choose your location: <span class="text-red">*</span></h3></div>';
    for (var i = 0; i < res.length; i++) {
        str += '<div class="box" style="padding: 10px;"><input type="radio" onclick="selectedPlace($(this).attr(\'id\'))" name="location" id="';
        str += i + '" ';
        if (i == 0) {
            str += ' checked="true"';
        }
        str += '>' + res[i].formatted_address;
        str += '</div>';
    }
    drawRoute(res, 0);
    countPrice();
    if (isAddressChanged)
        if (signed) {
            if ($("#change_address_check_box").is(':checked'))
                $('#location').html(str);
        } else {
            $('#location').html(str);
        }
    isAddressChanged = false;
    selectWarehouse();
}

function selectWarehouse() {
    if (selectedWarehouseIndex == -1) {
        selectedWarehouseIndex = selectBestWarehouse();
        document.getElementById('start').options[selectedWarehouseIndex].selected = true;
        changeWarehouseInfo();
    }
}

function countPrice() {
    var pricePerKm = $("#start").find(":selected").attr('shipmentRate');
    var dist = $("#distance").text();
    var ship_price = Math.round(dist * pricePerKm);
    var cost_of_commodities = new Number($("#commodities_cost").html());
    $("#shipping_price").html("" + ship_price);
    $("#dist_value").html(Math.round(dist));
    $("#total_cost").html(ship_price + cost_of_commodities);

}

function changeWarehouseInfo() {
    var shipmentRate = $("#start").find(":selected").attr('shipmentRate');
    var shipmentSpeed = $("#start").find(":selected").attr('shipmentSpeed');
    $("#speedShipment").html(shipmentSpeed);
    $("#pricePerKm").html(shipmentRate);
}

function initFields(country, city, street, building, flat) {
    $("#country").val(country);
    $("#city").val(city);
    $("#street").val(street);
    $("#building").val(building);
    $("#flat").val(flat);
}

function drawRoute(res, index) {
    setMarkerPosition(res, index);
    calcRouteFromWarehouse();
}

function changeAddress() {
    var unchecked = $("#change_address_check_box").is(':checked');
    unchecked = !unchecked;

//    $("#country").attr('disabled', unchecked);
//    $("#city").attr('disabled', unchecked);
//    $("#street").attr('disabled', unchecked);
//    $("#building").attr('disabled', unchecked);
//    $("#flat").attr('disabled', unchecked);

    if (unchecked) {
        initFields(oldData[0], oldData[1], oldData[2], oldData[3], oldData[4]);
        $("#location").hide();
        $("#input-block").hide();
        $("#longitude").val(longitude);
        $("#latitude").val(latitude);
        updateLocation();
    } else {
        initFields(newData[0], newData[1], newData[2], newData[3], newData[4])
        updateLocation();
        $("#input-block").show();
    }
}

function selectedPlace(id) {
    setMarkerPosition(res, new Number(id));
    drawRoute(res, id);
    changeWarehouseInfo();
    for (var i = 0; i < res.length; i++) {
        if (document.getElementById('' + i).checked) {
            for (var k = 0; k < res[i].address_components.length; k++) {
                if (res[i].address_components[k].types[0] == "country")
                    $("#country").val(toTranslit(res[i].address_components[k].long_name));
                if (res[i].address_components[k].types[0] == "locality")
                    $("#city").val(toTranslit(res[i].address_components[k].long_name));
                if (res[i].address_components[k].types[0] == "route")
                    $("#street").val(toTranslit(res[i].address_components[k].long_name));
                if (res[i].address_components[k].types[0] == "street_number")
                    $("#building").val(toTranslit(res[i].address_components[k].long_name));
            }
        }
    }
}

function sendData(dataString) {
    $.ajax({
        type: "POST",
        url: "Order",
        data: dataString,
        success: function(data) {
            window.location.replace(data.link);
        }
    });
}

function order_btn_clicked(isSigned) {
    console.log('order button clicked');
    if (isEmptyFields()) {
        return;
    }
    var dataString = 'email=' + $('#email').val() +
            '&country=' + $('#country').val() +
            '&city=' + $('#city').val() +
            '&street=' + $('#street').val() +
            '&home=' + $('#building').val() +
            '&apartment=' + $('#flat').val() +
            '&latitude=' + $("#latitude").val() +
            '&longitude=' + $("#longitude").val() +
            '&warehouse=' + $('#start').find(':selected').attr('id') +
            '&distance=' + $('#dist_value').html() +
            '&comment=' + $('#comment_area').val() +
            '&subscribed=' + $("#notify_email_box").is(':checked') +
            '&isNewAddress=' + $("#change_address_check_box").is(':checked');

    if (checkValidate($("#city"), $("#cityTip"), addressPattern)
            & checkValidate($("#country"), $("#countryTip"), addressPattern)
            & checkValidate($("#street"), $("#streetTip"), addressPattern)
            & checkValidate($("#home"), $("#homeTip"), homePattern)
            & ($('#email').val() == "") || checkValidate($("#email"), $("#emailTip"), emailPattern) ) {
        sendData(dataString);
    }
}

window.onload = function() {
    updateLocation();
    changeWarehouseInfo();
    if ($('#email').val() == '') {
        $("#notify_email").hide();
    }
};

$(document).ready(function() {
    var country = $("#country");
    var city = $("#city");
    var street = $("#street");
    var home = $("#building");
    var appartment = $("#flat");
    var email = $("#email");

    var countryTip = $("#countryTip");
    var cityTip = $("#cityTip");
    var streetTip = $("#streetTip");
    var homeTip = $("#buildingTip");
    var appartmentTip = $("#flatTip");
    var emailTip = $("#emailTip");

    var addressPattern = "^[a-zA-Z ,.'-]+$";
    var homePattern = "^[a-zA-Z0-9,./'-]+$";
    var emailPattern = "(([A-Za-z])|(\\d)|([-_.]))+@([A-Za-z])+[.]([A-Za-z]){2,4}";

    city.keyup(function() {
        checkValidate(city, cityTip, addressPattern);
        updateLocation();
    });
    country.keyup(function() {
        checkValidate(country, countryTip, addressPattern);
        updateLocation();
    });
    street.keyup(function() {
        checkValidate(street, streetTip, addressPattern);
        updateLocation();
    });
    home.keyup(function() {
        checkValidate(home, homeTip, homePattern);
        updateLocation();
    });
    appartment.keyup(function() {
        checkValidate(appartment, appartmentTip, homePattern);
        if (appartment.val() == "") {
            appartment.css("border-color", "#79c30c");
            appartmentTip.html("");
        }
    });
    email.keyup(function() {
        checkValidate(email, emailTip, emailPattern);        
        if (email.val() == "") {
            email.css("border-color", "#79c30c");
            emailTip.html("");
        }
    });

    initFields(oldData[0], oldData[1], oldData[2], oldData[3], oldData[4]);
    $("#location").hide();

    latitude = $("#latitude").val();
    longitude = $("#longitude").val();

    if (typeof change_address_check_box == "undefined")
        $("#input-block").show();
    else
        $("#input-block").hide();
});